package com.llkj.qingnianguoxue.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.jm.chat.activity.ChatActivity;
import com.jm.chat.activity.SearchMoreGroupActivity;
import com.jm.chat.application.JGApplication;
import com.jm.chat.entity.Event;
import com.jm.chat.entity.EventType;
import com.jm.chat.utils.HandleResponseCode;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.MyFriendsAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.bean.MyFriendListBean;
import com.llkj.qingnianguoxue.circle.MemberWarningActivity;
import com.llkj.qingnianguoxue.circle.MyChatActivity;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.android.eventbus.EventBus;
import cn.jpush.im.api.BasicCallback;

import static com.llkj.qingnianguoxue.circle.MyChatActivity.APP_KEY;

/**
 * 我的好友
 */
public class MyFriendsActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private static final int REQUEST_CHAT_CODE = 9170;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvMessage;
    private MyFriendsAdapter friendsAdapter;
    private List<MyFriendListBean.FriendBean> friendData;
    private int totalSize, mPage, mCurrentPosition;
    private String mCategoryType;//操作类型，1邀请好友

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_friends);
        setTitle("我的好友", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, TITLE_TYPE_TEXT, null);
        Intent intent = getIntent();
        mCategoryType = intent.getStringExtra("categoryType");

        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvMessage = (RecyclerView) findViewById(R.id.recyclerView);
        lvMessage.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        friendData = new ArrayList<>();
        friendsAdapter = new MyFriendsAdapter(R.layout.item_my_friends, friendData);
        if("1".equals(mCategoryType)){
            friendsAdapter.setDragLock(true);
        }
        lvMessage.setAdapter(friendsAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        friendsAdapter.setOnLoadMoreListener(this);
//        lvMessage.addOnItemTouchListener(new OnItemLongClickListener() {
//            @Override
//            public void onSimpleItemLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
//                mCurrentPosition = i;
//                MyFriendListBean.FriendBean friendBean = friendData.get(i);
//                dialogConfirm("您要删除好友" + friendBean.getUsername() + "吗？", null, "取消", "删除").show();
//            }
//        });

        lvMessage.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if(view.getId()==R.id.tvDelItem){
                    mCurrentPosition = i;
                    MyFriendListBean.FriendBean friendBean = friendData.get(i);
                    dialogConfirm("您要删除好友" + friendBean.getUsername() + "吗？", null, "取消", "删除").show();
                }
            }
        });
        lvMessage.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                MyFriendListBean.FriendBean friendBean = friendData.get(i);
//                if("1".equals(mCategoryType)){
//                    dialogConfirm("您要向好友" + friendBean.getUsername() + "发出邀请吗？",
//                            null, "取消", "确定").show();
//                }else{
                    MyChatActivity.startSingleChat(MyFriendsActivity.this,friendBean.getUsername(),
                            friendBean.getJg_id(),friendBean.getFriend_id());
//                }
            }
        });

    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        MyFriendListBean.FriendBean friendBean = friendData.get(mCurrentPosition);
        if("1".equals(mCategoryType)){//邀请好友进群
//            try {
//                sendInviteEntryCircle(friendBean);
//            }catch(Exception e){}
        }else {
            loadWaitDialog();
            HttpMethod.delFriend(this, this, friendBean.getFriend_id());
        }
    }

//    private void sendInviteEntryCircle(MyFriendListBean.FriendBean friendBean){
//        loadWaitDialog();
//        String circleId = getIntent().getStringExtra("circleId");
//        String circleName = getIntent().getStringExtra("circleName");
//        String circleCorver = getIntent().getStringExtra("circleCover");
//        String circlePrice = getIntent().getStringExtra("circlePrice");
//        //把名片的userName和appKey通过extra发送给对方
//        TextContent content = new TextContent("邀请好友进圈子");
//        content.setStringExtra("businessCard", "businessCard");
//        content.setStringExtra("userName",circleName);
//        content.setStringExtra("circleId",circleId);
//        content.setStringExtra("circleName",circleName);
//        content.setStringExtra("circleCover",circleCorver);
//        content.setStringExtra("circlePrice",circlePrice);
//        Conversation conversation = JMessageClient.getSingleConversation(friendBean.getJg_id(), APP_KEY);
//        if (conversation == null) {
//            conversation = Conversation.createSingleConversation(friendBean.getJg_id(),APP_KEY);
//            EventBus.getDefault().post(new Event.Builder()
//                    .setType(EventType.createConversation)
//                    .setConversation(conversation)
//                    .build());
//        }
//        Message textMessage = conversation.createSendMessage(content);
//        MessageSendingOptions options = new MessageSendingOptions();
//        options.setNeedReadReceipt(true);
//        JMessageClient.sendMessage(textMessage, options);
//        textMessage.setOnSendCompleteCallback(new BasicCallback() {
//            @Override
//            public void gotResult(int i, String s) {
//                dismissWaitDialog();
//                if (i == 0) {
//                    Toast.makeText(MyFriendsActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
//                } else {
//                    HandleResponseCode.onHandle(MyFriendsActivity.this, i, false);
//                }
//            }
//        });
//    }

    @Override
    public void onLoadMore() {
        mPage++;
        getFriendsData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getFriendsData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, friendsAdapter, null, lvMessage, totalSize);
    }

    /**
     * 获取好友数据
     */
    private void getFriendsData() {
        HttpMethod.userFriend(this, this, String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_USER_USER_FRIEND) {
            MyFriendListBean friendListBean = GsonUtil.GsonToListBean(data, MyFriendListBean.class);
            if (friendListBean != null) {
                totalSize = Integer.parseInt(friendListBean.getNum());
                if (mPage == 1) {
                    friendData.clear();
                    LoadDataHelper.refreshComplete(friendsAdapter, friendData, refreshLayout, lvMessage);
                } else {
                    friendsAdapter.setEnableLoadMore(true);
                    friendsAdapter.loadMoreComplete();
                }
                if(friendListBean.getList()!=null && friendListBean.getList().size()>0){
                    friendData.addAll(friendListBean.getList());
                }
                friendsAdapter.notifyDataSetChanged();
            }
        } else if (method == HttpMethod.HTTP_USER_DEL_FRIEND) {//8.6删除好友
            MyFriendListBean.FriendBean friendBean = friendData.get(mCurrentPosition);
            String friendId = friendBean.getJg_id();
            friendData.remove(mCurrentPosition);
            friendsAdapter.notifyDataSetChanged();

            //删除和某个user会话
            JMessageClient.deleteSingleConversation(friendId,null);
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(this, message);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == REQUEST_CHAT_CODE){
            onRefresh();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
